package com.code.man.util;

import com.code.man.exception.RunException;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

/**
 * 配置模板路径
 *
 * @author Tiny</ br>
 * mail: 114740122@qq.com
 * @version 1.0
 * @date 2018年7月10日  
 */
public class FreeMarkerUtils {

    private final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22);

    public FreeMarkerUtils(String dir) {
        //指定加载模板所在的路径
        TemplateLoader templateLoader;
        try {
            templateLoader = new FileTemplateLoader(new File(dir));
        } catch (IOException e) {
            throw new RunException(e);
        }
        CONFIGURATION.setTemplateLoader(templateLoader);
        CONFIGURATION.setDefaultEncoding("UTF-8");
        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
    }

    public FreeMarkerUtils(Class<?> resourceLoaderClass, String basePackagePath) {
        //从jar包中加载模板
        CONFIGURATION.setClassForTemplateLoading(resourceLoaderClass, basePackagePath);
        CONFIGURATION.setDefaultEncoding("UTF-8");
        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
    }

    /**
     * 生成文件
     *
     * @param templateName
     * @param outputPath
     * @param fileName
     * @param dataMap
     */
    public void generateFileByTemplate(String templateName, String outputPath, String fileName, Map<String, Object> dataMap)
            {
        FileOutputStream fileOutputStream = null;
        try {
            Template template = CONFIGURATION.getTemplate(templateName);

            File fileDir = new File(outputPath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }

            File file = new File(outputPath, fileName);
            if (file.exists()) {
                file.delete();
            }

            fileOutputStream = new FileOutputStream(file);
            Writer out = new BufferedWriter(new OutputStreamWriter(fileOutputStream, "utf-8"), 10240);
            template.process(dataMap, out);
        } catch (Exception e) {
            throw new RunException(e);
        } finally {
            if (null != fileOutputStream) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
